package net.zjitc.logincheckcode.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author Administrator
 * @Date 2020/6/4 15:46
 * 产生随机验证码
 **/
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 1、创建一图片对象  BufferedImage
           2、使用画笔  Graphics
              1）填充背景颜色
              2）画边框
              3）写字符（随机产生的）
              4）画干扰线  g.drawLine()
           3、将图片输出到页面显示 ImageIO
        * */
        /* 图片的宽高*/
        int width=80;
        int height=30;
        /*  1、创建一图片对象 */
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        /* 2、使用画笔功能 美化图片*/
        Graphics g=image.getGraphics();
        /* 设置画笔颜色 */
        g.setColor(Color.GRAY);
        /* 填充背景色*/
        g.fillRect(0,0,width,height);
        /* 画边框*/
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);
        /* 产生4个随机字符*/
        String s="abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random=new Random();
        /* sb用于存储产生的4个随机字符*/
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < 4; i++) {
            /* 产生随机索引*/
            int index = random.nextInt(s.length());
            /* 根据索引得到随机字符*/
            char ch = s.charAt(index);
            /* 保存随机字符*/
            sb.append(ch);
        }
        /* 将验证码字符串保存在session域对象*/
        request.getSession().setAttribute("session_code",sb.toString());
        g.setColor(Color.YELLOW);
        /* 设置字体*/
        g.setFont(new Font("黑体",Font.BOLD,22));
        /* 写随机字符*/
        g.drawString(sb.toString(),18,20);

        /* 3、将图片输出到页面显示 */
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
